from django import forms
from apps.forms import FormMixin
from django.core.cache import cache
from django.contrib.auth import get_user_model


User = get_user_model()


class LoginForm(forms.Form, FormMixin):

    telephone = forms.CharField(max_length=11)
    password = forms.CharField(max_length=20,min_length=6)
    remember = forms.IntegerField(required=False)


class RegisterForm(forms.Form, FormMixin):

    telephone = forms.CharField(max_length=11)
    username = forms.CharField(max_length=30)
    password1 = forms.CharField(max_length=20,min_length=6)
    password2 = forms.CharField(max_length=20,min_length=6)
    img_captcha = forms.CharField(max_length=4,min_length=4)

    def clean(self):
        cleaned_data = super(RegisterForm,self).clean()
        print('查看视图函数',cleaned_data)
        telephone = cleaned_data.get('telephone')
        password1 = cleaned_data.get('password1')
        password2 = cleaned_data.get('password2')
        img_captcha = cleaned_data.get('img_captcha').lower()

        if password1 != password2:
            raise forms.ValidationError('两次密码输出不一致')

        if not cache.get(img_captcha) or img_captcha != cache.get(img_captcha):
            raise forms.ValidationError('图形验证码错误！')

        exists = User.objects.filter(telephone=telephone).exists()
        if exists:
            forms.ValidationError('该手机号码已经被注册！')
        return cleaned_data